package com.ithema.dao.impl;

import com.ithema.dao.IAccountDao;
import com.ithema.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * 账户的业务层实现类
 *
 * @author SeRein
 */
public class IAccountDaoImpl implements IAccountDao {

    private QueryRunner runner;

    public void save(Account account) {
        try {
            int update = runner.update("insert account(name,money) values(?,?)", account.getName(), account.getMoney());
            System.out.println(update);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新
     *
     * @param account
     */
    public void update(Account account) {
        try {
            System.out.println(account.getId());
            System.out.println(account.getName());
            System.out.println(account.getMoney());
            int res = runner.update("update account set name=?,money=? where id = ? ", account.getName(), account.getMoney(), account.getId());
            System.out.println(res);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除
     *
     * @param accountId
     */
    public void delete(Integer accountId) {
        try {
            runner.update("delete from account where id = ?", accountId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过id查询
     *
     * @param accountId
     * @return
     */
    public Account findById(Integer accountId) {
        try {
            return runner.query("select id,name,money from account where id = ?", new BeanHandler<Account>(Account.class), accountId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询所有
     * @return
     * @throws SQLException
     */
    public List<Account> findAll() throws SQLException {
        System.out.println("代码执行到这");
        //BeanListHandler：将结果集中的每一行数据都封装到一个对应的JavaBean实例中，存放到List里。//重点
        return runner.query("select * from account", new BeanListHandler<Account>(Account.class));
    }

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }
}

